package logic

import (
	"context"
	"strings"

	"mall/service/backend/model"
	"mall/service/backend/rpc/internal/svc"
	"mall/service/backend/rpc/types/backend"

	"github.com/zeromicro/go-zero/core/logx"
)

type MenuListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewMenuListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MenuListLogic {
	return &MenuListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *MenuListLogic) MenuList(in *backend.MenuListRequest) (*backend.MenuListResponse, error) {
	logx.Infof("MenuListRequest : %+v ", in)

	var orderBys []string
	if len(in.OrderBy) > 0 {
		for _, orderBy := range in.OrderBy {
			if orderBy.Field == "id" {
				var order string = " ASC"
				if orderBy.Order == "1" {
					order = " DESC"
				}
				orderBys = append(orderBys, model.BackendMenuColumns.MenuID + order)
			} else if orderBy.Field == "menuOrder" {
				var order string = " ASC"
				if orderBy.Order == "1" {
					order = " DESC"
				}
				orderBys = append(orderBys, model.BackendMenuColumns.MenuOrder + order)
			}
		}
	}

	var stati string
	if len(in.FilterBy) > 0 {
		for _, filterBy := range in.FilterBy {
			if filterBy.Field == "status" {
				stati = filterBy.In
			}
		}
	}

	menuList, count, err := l.svcCtx.BackendMenu.GetList(l.ctx, model.M{
		"page":                            in.Current,
		"pageSize":                        in.PageSize,
		model.BackendMenuColumns.MenuID:   in.MenuId,
		model.BackendMenuColumns.ParentID: in.Pid,
		model.BackendMenuColumns.Name:     in.Name,
		model.BackendMenuColumns.Path:     in.Path,
		model.BackendMenuColumns.API:      in.Api,
		model.BackendMenuColumns.URL:      in.Url,
		model.BackendMenuColumns.Type:     in.Type,
		model.BackendMenuColumns.Status:   in.Status,
		"orderBy":                         strings.Join(orderBys, ","),
		"stati":                           stati,
	}, 1)
	if err != nil {
		return nil, err
	}

	var menus []*backend.MenuListItem
	if len(menuList) > 0 {
		for _, menu := range menuList {
			menus = append(menus, &backend.MenuListItem{
				Id:        int64(menu.MenuID),
				ParentId:  int64(menu.ParentID),
				Name:      menu.Name,
				Type:      int32(menu.Type),
				Status:    int32(menu.Status),
				DelStatus: int32(menu.DelStatus),
				Icon:      menu.Icon,
				PicUrl:    menu.PicURL,
				Path:      menu.Path,
				Api:       menu.API,
				Url:       menu.URL,
				MenuOrder: int32(menu.MenuOrder),
				CreatedAt: menu.CreatedAt.Format("2006-01-02 15:04:05"),
				UpdatedAt: menu.UpdatedAt.Format("2006-01-02 15:04:05"),
			})
		}
	}

	return &backend.MenuListResponse{
		Total: count,
		List:  menus,
	}, nil
}
